const path = require('path')
const Multer = require('koa-multer')
const Jimp = require('jimp')
const { AVATAR_PATH, WALL_PATH, PIC_PATH } = require('../app/file-path')

// 头像上传
const avatarUpload = Multer({ dest: AVATAR_PATH })
const avatarHandler = avatarUpload.single('avatar')

// 壁纸上传
const wallUpload = Multer({ dest: WALL_PATH })
const wallHandler = wallUpload.single('wall')

// 配图上传
const picUpload = Multer({ dest: PIC_PATH })
const picHandler = picUpload.array('pic', 9)

// 图片压缩
const picResize = async (ctx, next) => {
  // 1.获取所有图像信息
  const files = ctx.req.files
  // 2.处理图像
  for (let file of files) {
    const destPath = path.join(file.destination, file.filename)
    Jimp.read(file.path).then(image => {
      // image.resize(1280, Jimp.AUTO).write(`${destPath}-lg`)
      // image.resize(640, Jimp.AUTO).write(`${destPath}-ml`)
      image.resize(320, Jimp.AUTO).write(`${destPath}-sm`)
    })
  }
  // 3.执行下一步
  await next()
}

module.exports = {
  avatarHandler,
  wallHandler,
  picHandler,
  picResize
}
